
package com.rt.appauthorize;

import com.rt.schedulenew.utils.coder.DefaultSecurityCoderUtil;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.Enumeration;
import java.util.stream.Collectors;
import java.util.List;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileWriter;
import java.io.File;

import org.slf4j.Logger;


/***
 * 获取认证序列号
 */
public class AppAuthSerialNumberUtil {
    private static Logger log = LoggerFactory.getLogger(AppAuthSerialNumberUtil.class);

    public static String getMotherboardSN() {
        String result = "";
        try {
            File file = File.createTempFile("realhowto", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new FileWriter(file);
            String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\nSet colItems = objWMIService.ExecQuery _ \n   (\"Select * from Win32_BaseBoard\") \nFor Each objItem in colItems \n    Wscript.Echo objItem.SerialNumber \n    exit for  ' do the first cpu only! \nNext \n";
            fw.write(vbs);
            fw.close();
            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.trim();
    }

    public static String getMac() {
        ArrayList<String> tmpMacList = new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            StringBuilder sb = new StringBuilder();
            while (en.hasMoreElements()) {
                NetworkInterface networkInterface = en.nextElement();
                List<InterfaceAddress> addresses = networkInterface.getInterfaceAddresses();
                for (InterfaceAddress addr : addresses) {
                    InetAddress ip = addr.getAddress();
                    NetworkInterface network = NetworkInterface.getByInetAddress(ip);
                    if (network == null) {
                        continue;
                    }
                    byte[] mac = network.getHardwareAddress();
                    if (mac == null) {
                        continue;
                    }
                    sb.delete(0, sb.length());
                    for (int i = 0; i < mac.length; ++i) {
                        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                    }
                    tmpMacList.add(sb.toString());
                }
            }
        } catch (Exception e) {
            AppAuthSerialNumberUtil.log.error("获取mac地址失败,错误原因：{}", (Object) e.getMessage());
            return null;
        }
        if (tmpMacList.size() <= 0) {
            return null;
        }
        List<String> unique = tmpMacList.stream().distinct().collect(Collectors.toList());
        String macAddr = "";
        int j = 0;
        for (String addr2 : unique) {
            if (++j == unique.size()) {
                macAddr += addr2;
            } else {
                macAddr = macAddr + addr2 + ",";
            }
        }
        return macAddr;
    }

    public static String getDiskTotalSpace(String diskName) {
        File disk = new File(diskName);
        return String.valueOf(disk.getTotalSpace());
    }

    public static String executeLinuxCmd(String cmd) {
        try {
            log.info("got cmd job : " + cmd);
            Runtime run = Runtime.getRuntime();
            Process process = run.exec(cmd);
            InputStream in = process.getInputStream();
            BufferedReader bs = new BufferedReader(new InputStreamReader(in));
            StringBuffer out = new StringBuffer();
            byte[] b = new byte[8192];
            int n;
            while ((n = in.read(b)) != -1) {
                out.append(new String(b, 0, n));
            }
            in.close();
            process.destroy();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getSerialNumber(String cmd, String record, String symbol) {
        String execResult = executeLinuxCmd(cmd);
        String[] split;
        String[] infos = split = execResult.split("\n");
        for (String info : split) {
            info = info.trim();
            if (info.indexOf(record) != -1) {
                info.replace(" ", "");
                String[] sn = info.split(symbol);
                return sn[1];
            }
        }
        return null;
    }

    public static Map<String, String> getAllSn() {
        String os = System.getProperty("os.name");
        os = os.toUpperCase();
        log.info(os);
        Map<String, String> snVo = new HashMap<String, String>();
        if ("LINUX".equals(os)) {
            log.info("=============>for linux");
            String mainboardNumber = getSerialNumber("dmidecode |grep 'Serial Number'", "Serial Number", ":");
            log.info("mainboardNumber : " + mainboardNumber);
            String mac = getSerialNumber("ifconfig -a", "ether", " ");
            snVo.put("mac", mac.toUpperCase().replace(" ", ""));
            snVo.put("mainboard", mainboardNumber.toUpperCase().replace(" ", ""));
        } else {
            log.info("=============>for windows");
            String mainboard = getMotherboardSN();
            String mac = getMac();
            log.info("主板  SN:" + mainboard);
            log.info("MAC  SN:" + mac);
            snVo.put("mac", mac.toUpperCase().replace(" ", ""));
            snVo.put("mainboard", mainboard.toUpperCase().replace(" ", ""));
        }
        return snVo;
    }

    public static String getMachineCode() {
        String os = System.getProperty("os.name");
        os = os.toUpperCase();
        String machineCode = "";
        String mac = "";
        String path = System.getProperty("user.dir");
        String diskTotalSpace = "";
        if ("LINUX".equals(os) || "MAC OS X".equals(os)) {
            mac = getSerialNumber("ifconfig -a", "ether", " ");
            diskTotalSpace = getDiskTotalSpace("/");
        } else {
            mac = getMac();
            int row = path.indexOf("\\");
            String disk = path.substring(0, row);
            diskTotalSpace = getDiskTotalSpace(disk);
        }
        machineCode = mac.toUpperCase().replace(" ", "") + "*" + path + "*" + diskTotalSpace;
        machineCode = DefaultSecurityCoderUtil.encryptAES(machineCode);
        return machineCode;
    }

    public static String getMachineCodeSimple() {
        String os = System.getProperty("os.name");
        os = os.toUpperCase();
        String machineCode = "";
        String path = System.getProperty("user.dir");
        String diskTotalSpace = "";
        if ("LINUX".equals(os) || "MAC OS X".equals(os)) {
            diskTotalSpace = getDiskTotalSpace("/");
        } else {
            int row = path.indexOf("\\");
            String disk = path.substring(0, row);
            diskTotalSpace = getDiskTotalSpace(disk);
        }
        machineCode = path + "*" + diskTotalSpace;
        machineCode = DefaultSecurityCoderUtil.encryptAES(machineCode);
        return machineCode;
    }
}
